package tts.controller.users;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.GroupsHome;
import tts.dao.RolesHome;
import tts.dao.UsersHome;
import tts.model.Users;

public class Insert extends RedirectAction {

	//fields
	private static final long serialVersionUID = -9037931792240948793L;
	@Autowired
	private UsersHome usersHome;
	@Autowired
	private RolesHome rolesHome;
	@Autowired
	private GroupsHome groupsHome;
	private Users userIns;
	private ArrayList<String> rstrings;
	private ArrayList<String> gstrings;


	//get & set	
	public Users getUserIns() {
		return userIns;
	}
	public void setUserIns(Users userIns) {
		this.userIns = userIns;
	}
	public ArrayList<String> getRstrings() {
		return rstrings;
	}
	public void setRstrings(ArrayList<String> rstrings) {
		this.rstrings = rstrings;
	}
	public ArrayList<String> getGstrings() {
		return gstrings;
	}
	public void setGstrings(ArrayList<String> gstrings) {
		this.gstrings = gstrings;
	}
	
	//methods
	public String insert() {
		try {
			this.userIns.setEnabled(true);
			for (String r : rstrings) {
				userIns.getRolesList().add(rolesHome.findByRoleName(r));
			}
			for (String g : gstrings) {
				userIns.getGroupsList().add(groupsHome.findByGroupName(g));
			}
			this.usersHome.insert(this.userIns);
		} catch (RuntimeException e) {
			if (e.getCause().getCause().getMessage().startsWith("Duplicate"))
				addFieldError("userIns.username", getText("val.duplicate.user"));
			else addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("user.inserted"));
		return SUCCESS;
	}
}